#%%
from DataGeter import parse_url
import re
import json
import requests
import time
import pandas as pd


#%%


def tickertoBar(df, pre=60, key="datetime"):
    """
    pre = 周期 = 1-30 60 120 D M
    key = key
    """
    col_L = df.columns.tolist()
    if "price" in col_L:
        col_high = "price"
        col_low = "price"
        col_open = "price"
        col_close = "price"
        # df[key] = df.datetime.apply(lambda x: ":".join(x.split(":")))
        # _df = df.groupby(key)
        # Tdf = _df.sum().copy()
    else:
        col_high = "high"
        col_low = "low"
        col_open = "open"
        col_close = "close"

    # --------------- #
    # 时间变换模块     #
    if re.search("(\d)", pre):
        df["temp"] = df[key].apply(lambda x: x.split(" ")[-1])
        df["temp2"] = df[key].apply(lambda x: "".join(x.split(" ")[0]))
        pre = int(pre.split("m")[0])
        if pre >= 60:
            if pre == 60:
                df["temp"] = df.temp.apply(lambda x: int("".join(x.split(":"))))
                df["temp"] = df.temp.apply(
                    lambda x: "0"
                    if x <= 103000
                    else ("1" if x <= 113000 else "2" if x <= 140000 else "3")
                )

            elif pre == 120:
                df["temp"] = df.temp.apply(
                    lambda x: "0" if int(x.split(":")[0]) < 13 else "1"
                )
            pre = pre / 60
        elif 0 < pre < 60:
            pre = pre / 60 * 100
            df["temp"] = df.temp.apply(
                lambda x: int(
                    int(x.split(":")[0]) * 60 * 100 + int(x.split(":")[1]) / 60 * 100
                )
            )
            df["temp"] = df.temp.apply(lambda x: str(int(round(float(x)) / pre)))
        df["temp"] = df.temp2 + " " + df.temp
    elif "D" in pre.upper():
        df["temp"] = df[key].apply(lambda x: x.split(" ")[0])
    elif "M" in pre:
        df["temp"] = df[key].apply(lambda x: x.split("-")[0:-1])

    df.sort_values("datetime", inplace=True)
    # ---------------- #
    # gropuby 到输出   #
    _df = df.groupby("temp")
    Tdf = _df.sum().copy()
    Tdf["datetime"] = _df[key].last()

    Tdf["Avg_price"] = _df.amount.sum() / _df.volume.sum()
    Tdf["high"] = round(_df[col_high].max(), 2)
    Tdf["low"] = round(_df[col_low].min(), 2)
    Tdf["open"] = round(_df[col_open].first(), 2)
    Tdf["close"] = round(_df[col_close].last(), 2)

    l = []
    for num in range(Tdf.shape[0]):
        con = str(int(Tdf.iloc[num]["Avg_price"]))
        op = str(int(Tdf.iloc[num]["open"]))
        if int(con[0]) == 0:
            l.append(num)
    Tdf["Avg"] = Tdf["Avg_price"]
    Tdf["Avg"].iloc[l] = Tdf.iloc[l]["Avg_price"] * 100
    Tdf.iloc[l]["Avg"]
    Tdf.reset_index(inplace=True)
    if "price" in df.columns.tolist():
        Tdf.drop(["price", "change", "type"], inplace=True, axis=1)
    else:
        Tdf.drop(["code"], inplace=True, axis=1)
    Tdf.drop(["temp", "Avg_price"], inplace=True, axis=1)
    Tdf = Tdf.round(2)
    l = Tdf.columns.tolist()
    l.remove("datetime")
    l.insert(0, "datetime")
    Tdf = Tdf[l]
    Tdf.sort_values("datetime", inplace=True)

    return Tdf


df = pd.read_csv("000001.csv")
df = tickertoBar(df, pre="10")
df
#%%

#%%
stemp = int(time.time() * (10 ** 3))
print(len(str(stemp)))
print(stemp)
T = time.localtime(stemp * (10 ** (-3)))
print(T)
time.strftime("%Y-%m-%d %H:%M:%S", T)

#%%
header = {
    "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36",
    "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
    "Accept-Encoding": "gzip, deflate",
    "Accept-Language": "en-US,en;q=0.5",
}

url = "http://yunhq.sse.com.cn:32041//v1/sh1/line/"
# code = str(601398)
# "?callback=jQuery"
# time_stamp = "1608541410461" # timeStamp = 16位数
# "&begin=0&end=-1&select=time%2Cprice%2Cvolume&_=""
# "1608541410464"

# 112407743066542660044 "_1608541410461"
# 112403787097656785734 "_1608545225135"
# 11240837419092585838_1608545365639
# 112405953920629523836_1608545386590
# 112405886873726068012_1608545406417
# 112409104659691385864_1608545447059

# "11240" "0478301093202218""_""1608545666494"
# 8425 5617 7627 4582 _ 1608 3923 7627 0
#%%
sess = requests.session()
r = sess.get(url, headers=header)
r
# parse_url.parse_url(url, header)
# %%
con = r.content.decode("utf-8")
print(con)
# %%
alls = re.compile(r"^jQuery112407743066542660044_1608541410461.(.*).")
temp = alls.findall(con)[0]
temp
# %%
dic = json.loads(temp)
# %%
dic["line"]
# %%
